<template>
  <div>
    <div>
      <DynamicTable row-key="id" :scroll="{ x: 2000 }" header-title="未处结工单" show-index :data-request="loadTableData"
        :columns="columns" bordered size="small">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'workOrderNumber'">
            <a class="workOrderNumber" v-on:click="openMenuModal(record)">{{ record.workOrderNumber }} </a>
          </template>
        </template>
        <template #toolbar>
          <AButton color="rgb(64,169,255)" @click="mergeHandle"> 并单 </AButton>
          <AButton color="rgb(64,169,0)" @click="noMergeHandle"> 解除并单 </AButton>
        </template>
        
      </DynamicTable>
    </div>
    <div>
      <DraggableModal v-model:visible="processHisvisible" title="流转历史"
        :body-style="{ maxHeight: '500px', overflowY: 'auto' }" :destroyOnClose="true" :centered=false width="60%"
        :keyboard="false" :fullscreen=false :closable=true footer="">
        <processHistory :work-order-number="workOrderNumber" :instance-id="instanceId"></processHistory>
      </DraggableModal>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { baseColumns, pageDataObj, type TableColumnItem } from './columns';
import { workorderschemas } from '@/views/workorder/order/formSchemas';
import { dictPotionsListApi } from '@/api/workorder/select';
import { updateWorkOrder, createWorkOrder, listWorkOrderMerge, changeMergeWorkOrderHandle } from '@/api/workorder/order';
import { LoadDataParams, useTable } from '@/components/core/dynamic-table';
import { useFormModal } from '@/hooks/useModal/useFormModal';
import { getCategaryList } from '@/api/workorder/categary';
import { DraggableModal } from '@/components/core/draggable-modal';
import { listAttament } from '@/api/workorder/common/attachment';
import { getDeptList } from '@/api/system/dept';
import processHistory from '@/views/workorder/task/processHistory/index.vue';
import { ref } from 'vue';
import { string } from 'vue-types';
import { formatCategary2Tree } from '@/core/permission/utils';



defineOptions({
  name: 'SystemPermissionWorkOrder',
});

let masterNumber = ""; // 主单单号
let slaveNumber = ""; // 子单单号

const [DynamicTable, dynamicTableInstance] = useTable({
  formProps: {
    fieldMapToTime: [
      ['dispatchTime', ['dispatchStartTime', 'dispatchEndTime'], 'YYYY-MM-DD HH:mm:ss'],
    ],
  }
});
const [showModal] = useFormModal();
// 流转历史是否显示
const processHisvisible = ref(false);
let instanceId = ref(string);
let workOrderNumber = ref(string);

/**
 * @description 并单的方法
 */
const mergeHandle = async () => {
  getSelect()
  let params = { "masterNumber": masterNumber, "slaveNumber": slaveNumber, "opt": "merge" }
  await changeMergeWorkOrderHandle(params)
  dynamicTableInstance.reload();
}

/**
 * @description 取消并单的方法
 */
const noMergeHandle = async () => {
  getSelect()
  let params = { "masterNumber": masterNumber, "slaveNumber": slaveNumber, "opt": "unmerge" }
  await changeMergeWorkOrderHandle(params)
  dynamicTableInstance.reload();
}

/**
 * @description 获取列表上的选中状态
 */
const getSelect = async () => {
  masterNumber = slaveNumber = "";
  var radio = document.getElementsByName("masterNumber");
  for (var i = 0; i < radio.length; i++) {
    if (radio[i].checked == true) {
      masterNumber = radio[i].value;
      break;
    }
  }
  var check = document.getElementsByName("slaveNumber");
  for (var i = 0; i < check.length; i++) {
    if (check[i].checked == true) {
      slaveNumber += check[i].value + ",";
    }
  }
  slaveNumber = slaveNumber.substr(0, slaveNumber.length - 1)
}
/**
 * @deprecated 查询数据的服务
 */
const loadTableData = async (params: LoadDataParams) => {
  if (params.acceptTime || params.industryType || params.occAddress || params.workOrderNumber) {
    const data = await listWorkOrderMerge({
      ...params,
    });
    return data;
  }
}

/**
 * @description 打开新增/编辑弹窗
 */
const openMenuModal = async (record: Partial) => {
  const [formRef] = await showModal({
    modalProps: {
      title: `${record.id ? '查看' : '新增'}工单信息`,
      width: '60vh', 
      okButtonProps: { disabled: true },
      cancelText: '关闭',
      onFinish: async (values) => {
        record.id && (values.workOrderId = record.id);
        await (record.id ? updateWorkOrder : createWorkOrder)(values);
        dynamicTableInstance?.reload();
      },
    },
    formProps: {
      labelWidth: 100,
      schemas: workorderschemas,
    },
  });
  // 填充表单数据
  formRef?.setFieldsValue({
    ...record,
  });
  // 设置表单禁用属性
  formRef?.setSchemaFormProps({
    disabled: true,
    requiredMark: false,
  });
  // 非必填信息清除
  formRef?.updateSchema({
    field: 'remarks',
    componentProps: {
      placeholder: "",
    },
  })
  // 添加附件列表
  let data = await listAttament({ 'bussId': record.id });
  let initFileData = [];
  data.forEach((fileData) => {
    initFileData.push({
      uid: fileData.id,
      name: fileData.fileName,
      status: 'done',
    });
  })
  formRef?.updateSchema({
    field: 'attament',
    componentProps: {
      fileList: initFileData
    },
  })
};
// 自定义转码字典
dictPotionsListApi({ "code": 'workorder_type' }).then((res) => {
  pageDataObj.workOrderTypeDict = res.map((item) => ({
    label: item.name,
    value: item.code,
  }));
}).then(() => {
  // 改变搜索框数据
  dynamicTableInstance?.getQueryFormRef()?.updateSchema({
    field: `workOrderType`,
    componentProps: {
      options: pageDataObj.workOrderTypeDict,
    },
  });
});
dictPotionsListApi({ "code": 'info_serrces' }).then((res) => {
  pageDataObj.infoSerrcesTypeDict = res.map((item) => ({
    label: item.name,
    value: item.code,
  }));
});
dictPotionsListApi({ "code": 'region' }).then((res) => {
  pageDataObj.regionDict = res.map((item) => ({
    label: item.name,
    value: item.code,
  }));
}).then(() => {
  // 改变搜索框数据
  dynamicTableInstance?.getQueryFormRef()?.updateSchema({
    field: `region`,
    componentProps: {
      options: pageDataObj.regionDict,
    },
  });
});
dictPotionsListApi({ "code": 'workorder_status' }).then((res) => {
  pageDataObj.workOrderStatus = res.map((item) => ({
    label: item.name,
    value: item.code,
  }));
}).then(() => {
  // 改变搜索框数据
  dynamicTableInstance?.getQueryFormRef()?.updateSchema({
    field: `workOrderStatus`,
    componentProps: {
      options: pageDataObj.workOrderStatus,
    },
  });
});
getCategaryList({ "sysCode": 'workorder', 'visible': '0', 'categaryCode': 'industry_type' }).then((res) => {
  pageDataObj.industryTypeDict = res.map((item) => ({
    label: item.name,
    value: item.code,
  }));
  dynamicTableInstance?.getQueryFormRef()?.updateSchema({
    field: `industryType`,
    componentProps: {
      treeData: formatCategary2Tree(res, '0'),
    },
  });
});
getDeptList().then((res) => {
  pageDataObj.responsibleUnitDict = res.map((item) => ({
    label: item.name,
    value: item.id,
  }));
})


const columns: TableColumnItem[] = [
  ...baseColumns,
  {
    title: '操作',
    width: 100,
    dataIndex: 'ACTION',
    hideInSearch: true,
    align: 'center',
    fixed: 'right',
    actions: ({ record }) => [
      {
        label: '流转历史',
        ifShow: ()=> record.consStatus == '0' ||  record.consStatus == '2',
        onClick: () => processHisvisibleModel(record),
      },
    ],
  },
];

async function processHisvisibleModel(record) {
  // 打开操作框选择页面
  processHisvisible.value = true;
  instanceId = record.instanceId;
  workOrderNumber = record.workOrderNumber;
}
</script>
<style lang="less">
.ant-input-number {
  width: 100%;
}

.workOrderNumber {
  color: #1890ff;
}

.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.ant-tooltip-inner{
  width: 500px;
}
</style>

